package com.tfjybj.itoo.teach.provider.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.dmsdbj.itoo.tool.base.service.impl.BaseServicePlusImpl;
import com.dmsdbj.itoo.tool.business.ItooResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tfjybj.itoo.teach.entity.AdmTeachClassEntity;
import com.tfjybj.itoo.teach.model.ClassModel;
import com.tfjybj.itoo.teach.model.StudentModel;
import com.tfjybj.itoo.teach.provider.dao.AdmTeachClassDao;
import com.tfjybj.itoo.teach.provider.dao.StudentTeachClassDao;
import com.tfjybj.itoo.teach.provider.service.AdmTeachClassService;
import com.tfjybj.itoo.teach.provider.service.ClassService;
import com.tfjybj.itoo.teach.provider.service.StudentService;
import com.tfjybj.itoo.teach.template.AdmTeachClassTemplate;
import lombok.extern.slf4j.Slf4j;
import org.jplus.hyberbin.excel.utils.ExcelUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.*;

import static com.tfjybj.itoo.teach.provider.until.DemoConstants.*;


/**
 * AdmTeachClassService接口实现类
 * ${base}表
 *
 * @author 田成荣
 * @version 2.0.0
 * @since 2.0.0 2018-11-08 19:34:10
 */
@Service("admTeachClassService")
@Slf4j
public class AdmTeachClassServiceImpl extends BaseServicePlusImpl<AdmTeachClassDao, AdmTeachClassEntity> implements AdmTeachClassService {

    //region 模板生成

    @Resource
    private AdmTeachClassDao admTeachClassDao;

    @Resource
    private AdmTeachClassService admTeachClassService;

    @Resource
    private StudentTeachClassDao studentTeachClassDao;

    @Resource
    private ClassService classService;

    @Resource
    private StudentService studentService;

    @Resource
    private RedisTemplate<String, AdmTeachClassTemplate> redisTemplate;

    @Override
    public PageInfo<AdmTeachClassEntity> queryByLikeClassId(String classId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(admTeachClassDao.queryLikeClassId(classId));
    }
    //endregion

    /* **********************************以下为非模板生成的内容********************************* */


    @Override
    public List<String> queryAdmTeachclass(String teachClassId) {
        return studentTeachClassDao.queryClassIdsByTeachClassId(teachClassId);
    }


    @Override
    public PageInfo<ClassModel> queryClassInfoByTeacherClassId(String teachClassId, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        return new PageInfo<>(admTeachClassDao.queryClassInfoByTeacherClassId(teachClassId));
    }


    @Override
    public String queryAcademyNameByProfessionId(String professionId) {
        return admTeachClassDao.queryAcademyNameByProfessionId(professionId);
    }


    @Override
    public String queryClassNameByStudentId(String studentId) {
        return admTeachClassDao.queryClassNameByStudentId(studentId);
    }


    @Override
    public String insertTeachClassIdByClassIds(List<String> classIds) {
        List<AdmTeachClassEntity> admTeachClassEntityList = new ArrayList<>();
        String teachClassId = IdWorker.getIdStr();
        List<String> classIdList = new ArrayList<>(classIds);
        classIdList.forEach(e -> {
            AdmTeachClassEntity admTeachClassEntity = new AdmTeachClassEntity();
            admTeachClassEntity.setId(IdWorker.getIdStr());
            admTeachClassEntity.setOperator("大米时代");
            admTeachClassEntity.setTeachClassId(teachClassId);
            admTeachClassEntity.setClassId(e);
            admTeachClassEntity.setIsDelete(0);
            admTeachClassEntityList.add(admTeachClassEntity);
        });
        Boolean size = this.saveOrUpdateBatch(admTeachClassEntityList);
        if (size) {
            return teachClassId;

        } else {
            return "多个行政班合成一个上课班失败";
        }

    }



    @Override
    public PageInfo<StudentModel> queryStudentInfoByClassId(String classId, Integer pageNum, Integer pageSize) {

        return studentService.queryStudentInfoByClassId(classId, pageNum, pageSize);

    }



    @Override
    public PageInfo<StudentModel> queryStudentInfoByCodeAndNameStrLike(String strLike, Integer pageNum, Integer pageSize) {
        strLike = strLike.trim();
        PageHelper.startPage(pageNum, pageSize);
        return studentService.queryStudentInfoByCodeAndNameStrLike(pageNum,pageSize,strLike);
    }



    @Override
    public PageInfo<ClassModel> queryAdmTeachClassInfoByNameStrLike(String strLike, String teachClassId, Integer pageNum, Integer pageSize) {
        strLike = strLike.trim();
        teachClassId = teachClassId.trim();
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(admTeachClassDao.queryAdmTeachClassInfoByNameStrLike(strLike, teachClassId));
    }


    @Override
    public PageInfo<ClassModel> queryAdmTeachClassInfoByCodeAndNameStrLike(String classCode, String className, String teachClassId, Integer pageNum, Integer pageSize) {
        classCode = classCode.trim();
        className = className.trim();
        teachClassId = teachClassId.trim();
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(admTeachClassDao.queryAdmTeachClassInfoByCodeAndNameStrLike(classCode, className, teachClassId));
    }



    @Override
    public boolean deleteAdmTeachclass(List<String> classIds, String teachClassId, String operator) {
        List<String> ids=admTeachClassService.queryIdsByclassIdsAndTeachClassId(classIds,teachClassId);
        return admTeachClassService.removeByIds(ids);
    }


    @Override
    public boolean deleteSingleAdmTeachclass(String classId, String teachClassId, String operator){
        String id=admTeachClassService.queryIdByClassIdAndTeachClassId(classId,teachClassId);
        return admTeachClassService.removeById(id);
    }




    @Override
    public int insertAdmTeachClass(List<String> classIds, String teachClassId, String operator) {

        List<String> classIdList = new ArrayList<>(classIds);
        int size;
        size = admTeachClassDao.deleteAdmTeachclass(classIdList, teachClassId, operator);
        return size;

    }


    @Override
    public int deleteAdmTeachClassByStudentIds(List<String> studentIds, String teachClassId, String operator) {

        return studentTeachClassDao.deleteStudentTeachClass(studentIds, teachClassId, operator);

    }

    @Override
    public boolean downErrorList(String errorListId, HttpServletResponse response) {
        // redis 取出没有成功导入的人员信息
        Set set = redisTemplate.opsForZSet().range(errorListId, 0, -1);
        List<AdmTeachClassTemplate> admTeachClassTemplate = new ArrayList<>(set);
        // 清空redis数据
        redisTemplate.delete(errorListId);

        //导出
        if (admTeachClassTemplate.size() == 0) {
            return false;
        }
        Map<Serializable, Serializable> errorMap = new HashMap<>(16);
        errorMap.put(SHEET_NAME, "上课班和行政班关系表模板");
        //需要导入的字段
        errorMap.put(COLUMNS, new String[]{"classCode", "className","failReason"});
        //表格的标题
        errorMap.put(TITLE, "上课班和行政班关系");
        errorMap.put(NAME, "上课班和行政班关系模板");
        errorMap.put(DATA_LIST, (Serializable) admTeachClassTemplate);
        try {
            ExcelUtil.exportExcel(errorMap, response);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @Override
    public boolean downLoadAdmTeachClassTemplate(HttpServletResponse response) {
        Map<Serializable, Serializable> map = new HashMap<>(16);
        List<AdmTeachClassTemplate> templateList = new ArrayList<>();
        AdmTeachClassTemplate admTeachClassTemplate = new AdmTeachClassTemplate();
        //添加下载模板范例
        admTeachClassTemplate.setClassCode("02114151");
        admTeachClassTemplate.setClassName("15级人文教育1班");
        templateList.add(admTeachClassTemplate);
        //sheet的名字
        map.put(SHEET_NAME, "上课班和行政班关系表模板");
        //需要导入的字段
        map.put(COLUMNS, new String[]{"classCode", "className"});
        //表格的标题
        map.put(TITLE, "上课班和行政班关系");
        map.put(NAME, "上课班和行政班关系模板");
        map.put(DATA_LIST, (Serializable) templateList);
        try {
            ExcelUtil.exportExcel(map, response);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    @Override
    public ItooResult importAdmTeachClassByTemplate(MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response, String teachClassId) {
        response.setContentType("UTF-8");
        try {
            //校验文件是否存在
            String fileName = multipartFile.getOriginalFilename();
            if (fileName == null) {
                log.error("导入失败,fileName is null!");
                return ItooResult.build(ItooResult.FAIL, "传入的文件为空！");
            }

            //EXCEL解析成List
            Map<Serializable, Serializable> map = new HashMap<>(4);
            map.put(SHEET_NAME, "上课班和行政班关系表模板");
            map.put(CLASS, AdmTeachClassTemplate.class);
            List<AdmTeachClassTemplate> admTeachClassTemplateList = ExcelUtil.importExcel(Objects.requireNonNull(fileName), map, request, response);

            if (admTeachClassTemplateList.size() == 0) {
                return ItooResult.build(ItooResult.FAIL, "导入的数据为空，请填写！");
            }
            //定义导入的错误数据集合并存redis中形式的<String,admTeachClassTemplate>
            List<AdmTeachClassTemplate> errorTPTList = new ArrayList<>();
            String errorTPTListId = IdWorker.getIdStr();
            Long size = redisTemplate.opsForZSet().size(errorTPTListId);
            size = size == null ? 0L : size;

            for (AdmTeachClassTemplate excelTPT : admTeachClassTemplateList) {

                if (!this.verify(excelTPT,teachClassId)) {
                    AdmTeachClassTemplate admTeachClassT = new AdmTeachClassTemplate();
                    BeanUtils.copyProperties(excelTPT, admTeachClassT);

                    errorTPTList.add(admTeachClassT);
                    redisTemplate.opsForZSet().add(errorTPTListId, admTeachClassT, size + 1);
                    continue;
                }

                AdmTeachClassEntity admTeachClassEntity = insertValue(excelTPT,teachClassId);


                this.save(admTeachClassEntity);
            }
            //不符合条件的信息返回
            if (errorTPTList.size() > 0) {
                return ItooResult.build("0001","部分导入失败",errorTPTListId);
            }
        }
        catch(Exception e)
        {
            return ItooResult.build(ItooResult.FAIL, "导入数据异常！",e);
        }
        return ItooResult.build(ItooResult.SUCCESS, "导入数据成功！");

            }


    private AdmTeachClassEntity insertValue(AdmTeachClassTemplate admTeachClassTemplate, String teachClassId){
        AdmTeachClassEntity admTeachClassEntity = new AdmTeachClassEntity();
        //将导入内容放到entity中对应的属性中去
        String classId=classService.queryClassesByCode(admTeachClassTemplate.getClassCode()).get(0).getId();

        BeanUtils.copyProperties(admTeachClassTemplate, admTeachClassEntity);
        //培养计划ID
        admTeachClassEntity.setId(IdWorker.getIdStr());
        //可用
        admTeachClassEntity.setIsDelete(0);
        //未排课
        admTeachClassEntity.setOperator("大米时代");
        admTeachClassEntity.setTeachClassId(teachClassId);
        admTeachClassEntity.setClassId(classId);
        return admTeachClassEntity;
    }


    private boolean verify (AdmTeachClassTemplate excelTPT , String teachClassId)
    {
        if (StringUtils.isEmpty(excelTPT.getClassCode())) {
            excelTPT.setFailReason("行政班代码未填写");
            log.warn("导入失败,行政班代码未填写,excelFooEntity-{}", excelTPT);
            return false;
        }

        if (StringUtils.isEmpty(excelTPT.getClassName())) {
            excelTPT.setFailReason("行政班名称未填写");
            log.warn("导入失败,行政班名称未填写,excelFooEntity-{}", excelTPT);
            return false;
        }
        AdmTeachClassEntity admTeachClassEntity = new AdmTeachClassEntity();
        //将导入内容放到entity中对应的属性中去
        BeanUtils.copyProperties(excelTPT, admTeachClassEntity);

        //培养计划ID
        admTeachClassEntity.setId(IdWorker.getIdStr());
        //可用
        admTeachClassEntity.setOperator("大米时代");
        //未删除
        admTeachClassEntity.setIsDelete(0);

        //通过行政班code获取行政班数据
        List<ClassModel> classModel = classService.queryClassesByCode(excelTPT.getClassCode());
        if (CollectionUtils.isEmpty(classModel)){

            excelTPT.setFailReason("找不到行政班code:" + excelTPT.getClassCode());
            log.warn("找不到行政班code:" + excelTPT.getClassCode()+ "-",excelTPT);
            return false;
        }

        admTeachClassEntity.setClassId(classModel.get(0).getId());

        //判断查询出的课程名称与导入时写入的课程名称是否相同
        if (!classModel.get(0).getName().equals(excelTPT.getClassName())){

            excelTPT.setFailReason("行政班代码:" + excelTPT.getClassCode() + " 所对应的行政班名称与输入的行政班名称 " + excelTPT.getClassName() + "不匹配");
            log.warn("行政班代码:" + excelTPT.getClassCode() + " 所对应的行政班名称与输入的行政班名称 " + excelTPT.getClassName() + "不匹配" + "-",excelTPT);
            return false;
        }

        //课程ID
        admTeachClassEntity.setClassId(classModel.get(0).getId());
        //课程类型ID
        admTeachClassEntity.setTeachClassId(teachClassId);

        //判断上课班-行政班是否已经存在
        String idIsExist = admTeachClassService.findIdIsExist(classModel.get(0).getId(), teachClassId);
        if (!StringUtils.isEmpty(idIsExist)){
            excelTPT.setFailReason("行政班:" + excelTPT.getClassName() + "已存在对应的上课班，不能重复添加 " );
            log.warn("行政班:" + excelTPT.getClassName() + "已存在对应的上课班，不能重复添加 " + "不匹配" + "-",excelTPT);
            return false;
        }
        return true;
    }



    @Override
    public String findIdIsExist (String classId,String teachClassId){
        return admTeachClassDao.findIdIsExist ( classId, teachClassId);
    }

    @Override
    public Boolean checkByclassIdandteachClassId(String classId, String teachClassId) {
        Boolean flagctcount=false;
        if(admTeachClassDao.checkByclassIdandteachClassId(classId,teachClassId)>0) {
            flagctcount=true;
        }
        return flagctcount;
    }

    @Override
    public List<String> queryIdsByclassIdsAndTeachClassId(List<String> classIds, String teachClassId){
        return admTeachClassDao.queryIdsByclassIdsAndTeachClassId(classIds,teachClassId);
    }

    @Override
    public String queryIdByClassIdAndTeachClassId(String classId,String teachClassId){
        return admTeachClassDao.queryIdByClassIdAndTeachClassId(classId,teachClassId);
    }
}


